<script>
import { reactive, ref } from "vue";
import { queryTradingApi } from "./api";
import Taro from "@tarojs/taro";
import profile from "@/components/Profile";
import TzVue, { useReachBottom, usePullDownRefresh } from "@/lib/TzVue";
import { useTzRouter } from "@/vhooks/useTzRouter";

export default new TzVue({
  name: "Bill",
  components: {
    profile,
  },
  setup() {
    const { EventChannel } = useTzRouter();
    const profileRef = ref(null);
    const state = reactive({
      billList: [],
      queryParams: {
        pageIndex: 1,
        pageSize: 20,
      },
    });

    usePullDownRefresh(() => {
      state.billList = [];
      state.queryParams.pageIndex = 1;
      queryBill();
      profileRef?.value?.refreshBaseData();
      Taro.stopPullDownRefresh();
    });

    useReachBottom(() => {
      state.queryParams.pageIndex += 1;
      queryBill();
      profileRef?.value?.refreshBaseData();
    });

    const queryBill = () => {
      Taro.showLoading();
      queryTradingApi(state.queryParams)
        .then((res) => {
          Taro.hideLoading();
          const { data, total_count } = res.data;
          const billList = data ? JSON.parse(data) : [];
          if (state.billList.length === total_count) {
            // 已加载全部数据
            Taro.showToast({
              title: "已经到底了",
              icon: "none",
              duration: 1000,
            });
          } else {
            state.billList.push(...billList);
          }
        })
        .catch(() => {
          Taro.hideLoading();
        });
    };
    queryBill(); // 首次加载账单数据

    const getCell = (configList) => {
      return configList.map((item) => (
        <tz-cell
          title={item.title}
          class={isNaN(item.value) ? "" : "money-color"}
        >
          {item.value}
        </tz-cell>
      ));
    };
    // 计算操作前金额保留原来的计算方法：交易前金额使用减，其他操作类型都使用加
    const beforeMoneyComputer = (amount, money, operator = "add") => {
      const balance =
        operator === "add"
          ? Math.round((amount + money).toFixed(2) * 100) / 100
          : Math.round((amount - money).toFixed(2) * 100) / 100;
      return balance;
    };

    const getBillItem = (billItemData) => {
      // 操作类型识别码常量
      const reCharge = ["X1_01", "X1_08"], // 充值
        deductions = [
          "C3_04",
          "H3_04",
          "C3_05",
          "H3_05",
          "2002B1",
          "2002B2",
          "2005B1",
          "2005B2",
          "200501",
        ], // 扣款
        refund = ["C3_04", "H3_04", "C3_05", "H3_05", "200501"]; // 退款

      const { mode, amount, money, add_time, remark } = billItemData;
      let handleText = ""; // 操作类型简写
      let configList = {};
      let backgroundColor = ""; // 图标的背景颜色

      if (reCharge.includes(mode)) {
        // 充值
        handleText = "充";
        configList = [
          {
            title: "充值后金额:",
            value: amount,
          },
          {
            title: "充值金额:",
            value: Math.abs(money),
          },
          {
            title: "充值前金额:",
            value: beforeMoneyComputer(amount, money),
          },
          {
            title: "充值时间:",
            value: add_time,
          },
          {
            title: "交易备注:",
            value: remark,
          },
        ];
        backgroundColor = "#13c100";
      } else if (
        deductions.includes(billItemData.mode) &&
        billItemData.money > 0
      ) {
        // 扣款
        const remarkText = {
          C3_04: "大陆确报申请捆绑",
          H3_04: "香港确报申请捆绑",
          C3_05: "大陆确报解除捆绑",
          H3_05: "香港确报解除捆绑",
          200501: "香港无缝CCRN申报费用",
        };
        handleText = "扣";
        configList = [
          {
            title: "扣款后金额:",
            value: amount,
          },
          {
            title: "扣款金额:",
            value: money,
          },
          {
            title: "扣款前金额:",
            value: beforeMoneyComputer(amount, money),
          },
          {
            title: "扣款时间:",
            value: add_time,
          },
          {
            title: "交易备注:",
            value: remarkText[mode] ? remarkText[mode] : "短信",
          },
        ];
        backgroundColor = "#01fef3";
      } else if (refund.includes(billItemData.mode) && billItemData.money < 0) {
        // 退款
        const remarkText = {
          C3_04: "大陆确报申请捆绑回滚退费",
          H3_04: "香港确报申请捆绑回滚退费",
          C3_05: "大陆确报解除捆绑回滚退费",
          H3_05: "香港确报解除捆绑回滚退费",
          200501: "香港无缝CCRN申报退费",
        };
        handleText = "退";
        configList = [
          {
            title: "退款后金额:",
            value: amount,
          },
          {
            title: "退款金额:",
            value: Math.abs(money),
          },
          {
            title: "退款前金额:",
            value: beforeMoneyComputer(amount, money),
          },
          {
            title: "退款时间:",
            value: add_time,
          },
          {
            title: "交易备注:",
            value: remarkText[mode],
          },
        ];
        backgroundColor = "red";
      } else {
        // 交易
        handleText = "交";
        configList = [
          {
            title: "交易后金额:",
            value: amount,
          },
          {
            title: "交易金额:",
            value: money,
          },
          {
            title: "交易前金额:",
            value: beforeMoneyComputer(amount, money, "cut"),
          },
          {
            title: "交易时间:",
            value: add_time,
          },
        ];
        backgroundColor = "orange";
      }
      return (
        <tz-view class="list-item" key={billItemData.id}>
          <tz-view
            class="list-item-icon"
            style={{ "background-color": backgroundColor }}
          >
            {handleText}
          </tz-view>
          <tz-view class="bill-item">{getCell(configList)}</tz-view>
        </tz-view>
      );
    };
    const handleClick = () => {
      Taro.navigateTo({
        url: "/pages/subUser/recharge/index",
      });
    };

    // 原系统规则：如果交易金额为0，页面就不显示这种消费记录
    return () => {
      return (
        <tz-view class="bill">
          <profile ref={profileRef} hideRechargeBtn></profile>
          <tz-button
            class="recharge-btn"
            type="danger"
            onClick={() => handleClick()}
          >
            立即充值
          </tz-button>
          <tz-view class="list-area">
            {state.billList
              .filter((item) => item.money !== 0)
              .map((item) => getBillItem(item))}
          </tz-view>
        </tz-view>
      );
    };
  },
});
</script>

<style lang="scss">
.bill {
  display: flex;
  flex-direction: column;
  align-items: center;

  .recharge-btn {
    width: 345px;
    margin-top: 20px;
    height: 44px;
  }
  .list-area {
    width: 100%;
    margin-top: 16px;
    .list-item {
      display: flex;
      padding: 10px 15px;
      border-bottom: 1px dashed $border-color;
      &:last-child {
        border-bottom: none;
      }
      &:nth-child(odd) {
        background-color: $help-color;
      }
      .list-item-icon {
        margin-right: 10px;
        color: $white;
        width: 38px;
        height: 38px;
        border-radius: 50%;
        line-height: 38px;
        text-align: center;
        background-color: $primary-color-active;
        font-size: 20px;
      }
      .bill-item {
        .tz-cell {
          font-size: 14px;
          line-height: 24px;
          .tz-cell-label {
            width: 100px;
            color: $info-color;
          }
          &.money-color {
            .tz-cell-value {
              color: $warning-color;
            }
          }
        }
      }
    }
  }
}
</style>
